﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Astor.Modules.DataSources.Models;
using System.Collections.ObjectModel;

namespace Astor.Modules.DataSources.Services
{
    public class DataSourcesService : IDataSourcesService
    {
        public DataSourcesService()
        {
            _dataSources = new ObservableCollection<DataSource>
            {
                new DataSource { Id = Guid.NewGuid(), Name = "Northwind", Url = @"http://services.odata.org/Northwind/Northwind.svc/" },
                new DataSource { Id = Guid.NewGuid(), Name = "Netflix", Url = @"http://odata.netflix.com/v1/Catalog/" }
            };
        }

        public ObservableCollection<DataSource> FindAll()
        {
            return _dataSources;
        }

        public DataSource Add(DataSource newDataSource) 
        {
            newDataSource.Id = Guid.NewGuid();
            _dataSources.Add(newDataSource);
            return newDataSource;
        }

        public DataSource Modify(DataSource dataSource)
        {
            if (_dataSources.Contains(dataSource))
            {
                return dataSource;
            }
            else
            {
                var existing = _dataSources.Where(d => d.Id == dataSource.Id).ToList();
                foreach (var ds in existing)
                    _dataSources.Remove(ds);
                _dataSources.Add(dataSource);
                return dataSource;
            }
        }

        public void Delete(DataSource dataSource)
        {
            _dataSources.Remove(dataSource);
        }

        public bool Exists(string name)
        {
            return (from d in _dataSources
                    where d.Name == name
                    select d).Count() > 0;
        }

        private ObservableCollection<DataSource> _dataSources;
    }
}
